package flextv.search.command {

import com.adobe.cairngorm.commands.ICommand;
import com.adobe.cairngorm.control.CairngormEvent;

import flextv.core.logic.Logger;
import flextv.core.logic.Util;
import flextv.search.event.InvokeSearchEvent;
import flextv.search.logic.ISearchService;
import flextv.search.logic.SearchModel;
import flextv.search.logic.SearchServices;

import mx.collections.ArrayCollection;
import mx.logging.ILogger;
import mx.rpc.IResponder;


/** @see: http://livedocs.adobe.com/flex/3/langref/mx/rpc/IResponder.html*/
public class InvokeSearchCommand implements ICommand, IResponder {
	
	private static const LOG: ILogger = Logger.getLog(InvokeSearchCommand);

	
	public function InvokeSearchCommand() { }


	public function execute(_event: CairngormEvent): void {
		const event: InvokeSearchEvent = _event as InvokeSearchEvent;
		LOG.debug("Executing [event=" + event + "].");
		
		
		SearchModel.instance.isSearchInProgress = true;
		SearchModel.instance.searchItems = null;
		// CursorManager.setBusyCursor();
		
		const s: ISearchService = SearchServices.instance.searchService;
		s.search(event.searchTerm, this);
	}
	
	
	public function result(_data: Object): void {
		if((_data is ArrayCollection) == false) {
			throw new ArgumentError("Expected argument 'data' of type ArrayCollection, but was: " + _data); // TODO get fullqualified classname
		}
		const data: ArrayCollection = _data as ArrayCollection;
		
		LOG.debug("result(data.length="+data.length+") invoked");
		
		SearchModel.instance.searchItems = data;
		
		SearchModel.instance.isSearchInProgress = false;
		// CursorManager.removeAllCursors();
	}
	
	
	public function fault(info: Object): void {
		Util.DEFAULT_FAULT_FUNCTION(info);
		
		SearchModel.instance.isSearchInProgress = false;
		// CursorManager.removeAllCursors();
		
		// TODO proper error handling
	}
	
	
}
}